import { getUserInfoApi, loginApi, getUserDetailByIdApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(data)
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
  },
  removeUserInfo(state) {
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  async login(store, data) {
    const res = await loginApi(data)
    // console.log(13, res)
    store.commit('setToken', res)
    localStorage.setItem('loginTime', Date.now())
    // loginApi(data).then(res => {
    //   console.log(7, res)
    //   store.commit('setToken', res.data.data)
    // })
  },
  async getUserInfo(store) {
    const res = await getUserInfoApi()
    const detail = await getUserDetailByIdApi(res.userId)
    // console.log(25, res)
    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  logOut(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
